package cn.czh0123.advice;

import cn.czh0123.exception.BusinessException;
import cn.czh0123.msg.UserCodeMsg;
import cn.czh0123.utils.ResultWrapper;
import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

	@ExceptionHandler(NotLoginException.class)
	public Object handlerNotLoginException(NotLoginException nle) {

	    log.error("全局异常拦截 NotLoginException !=> ", nle);
		// 判断场景值，定制化异常信息
/*		String message;
        switch (nle.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = "未提供token";
                break;
            case NotLoginException.INVALID_TOKEN:
                message = "token无效";
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = "token已过期";
                break;
            case NotLoginException.BE_REPLACED:
                message = "token已被顶下线";
                break;
            case NotLoginException.KICK_OUT:
                message = "token已被踢下线";
                break;
            default:
                message = "当前会话未登录";
                break;
        }*/
		return ResultWrapper.error(UserCodeMsg.NOT_LOGIN);
	}

    /**
     * 处理校验失败异常（json格式）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("全局异常拦截 MethodArgumentNotValidException !=> ", e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return ResultWrapper.error(message);
    }

    /**
     * 处理校验失败异常（表单格式）
     */
    @ExceptionHandler(BindException.class)
    public Object handleBindException(BindException e) {
        log.error("全局异常拦截 BindException !=> ", e);
        // 获取所有的错误信息
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ResultWrapper.error(message);
    }

    @ExceptionHandler(BusinessException.class)
    public Object handleBusinessException(BusinessException businessException){
        log.error("全局异常拦截 BusinessException !=> ", businessException);
        return ResultWrapper.error(businessException.getCodeMsg());
    }

    @ExceptionHandler(Exception.class)
    public Object handlerDefaultExt(Exception e, HttpServletResponse response) {
        log.error("全局异常拦截 Exception !=> ", e);
        response.setContentType("application/json; charset=UTF-8");
        return ResultWrapper.defaultError();
    }
}
